<script setup lang="ts" name="ProblemForm">
import { reactive, ref } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import {
  addProblemApi,
  getProblemDetailApi,
  updateProblemApi,
} from "@/addon/htscrm/api";
import { cloneDeep } from "lodash-es";
import { useRoute } from "vue-router";
import { t } from "@/lang";

const route = useRoute();
const defaultFormData: IProblemItem = {
  type: 1,
  content: "",
  sort: 0,
  daan: [],
  single_answer: "",
  huodong_id: 0,
  jieda: "",
  xuanxiang: ["", "", "", ""],
  status: 1,
};
/** 表单实例 */
const formRef = ref<FormInstance>();
/** 表单数据 */
const formData = ref<IProblemItem>({ ...defaultFormData });

// 表单规则
const formRules = reactive<FormRules>({
  content: [{ required: true, message: "请输入问题内容", trigger: "blur" }],
  xuanxiang: [{ required: true, message: "请输入选项内容", trigger: "blur" }],
  single_answer: [
    { required: true, message: "请选择单选答案", trigger: "blur" },
  ],
});

/**
 * @description 初始化
 * @param id ID
 */
function init(row?: IProblemItem) {
  formRef.value?.resetFields();
  if (row?.id) {
    getDetail(row.id);
  } else {
    formData.value = { ...defaultFormData };
  }
}

/**
 * @description 获取详情
 * @param id ID
 */
async function getDetail(id: IProblemItem["id"]) {
  const res = await getProblemDetailApi(id);
  // 单选取出答案
  if (res.data.type == 1) {
    res.data.single_answer = res.data.daan[0];
  }
  formData.value = res.data;
}

/**
 * @description 提交保存
 */
function submit() {
  return new Promise((resolve, reject) => {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        const params = cloneDeep(formData.value);
        // 新增活动ID
        params.huodong_id = params.huodong_id || Number(route.query.id);
        // 单选答案
        if (params.type === 1) {
          params.daan = [params.single_answer];
        }
        // 表单校验
        params.id
          ? await updateProblemApi(params)
          : await addProblemApi(params);
        ElMessage.success(t("save.success"));
        formData.value = {
          type: 1,
          content: "",
          sort: 0,
          daan: [],
          single_answer: "",
          huodong_id: 0,
          jieda: "",
          xuanxiang: ["", "", "", ""],
          status: 1,
        };
        resolve(true);
      } else {
        reject(new Error(t("form.validateError")));
      }
    });
  });
}

defineExpose({
  init,
  submit,
});
</script>

<template>
  <el-form
    class="f-form"
    ref="formRef"
    label-width="100px"
    :model="formData"
    :rules="formRules">
    <el-form-item
      label="问题类型"
      prop="type">
      <el-radio-group v-model="formData.type">
        <el-radio-button
          label="单选题"
          :value="1" />
      </el-radio-group>
    </el-form-item>
    <el-form-item
      label="问题内容"
      prop="content">
      <el-input
        v-model="formData.content"
        type="textarea"
        :rows="5"
        placeholder="请输入问题内容" />
    </el-form-item>
    <el-form-item label="选项">
      <div>
        <el-input
          class="mb-[10px]"
          :class="{
            active: formData.single_answer == ['A', 'B', 'C', 'D'][index],
          }"
          v-for="(item, index) in formData.xuanxiang"
          :key="index"
          v-model="formData.xuanxiang[index]"
          placeholder="请输入选项">
          <template #prepend>{{ ["A", "B", "C", "D"][index] }}</template>
        </el-input>
      </div>
    </el-form-item>
    <el-form-item
      label="答案"
      prop="single_answer">
      <el-radio-group v-model="formData.single_answer">
        <el-radio
          label="A"
          value="A" />
        <el-radio
          label="B"
          value="B" />
        <el-radio
          label="C"
          value="C" />
        <el-radio
          label="D"
          value="D" />
      </el-radio-group>
    </el-form-item>
    <el-form-item
      label="解答"
      prop="jieda">
      <el-input
        v-model="formData.jieda"
        type="textarea"
        :rows="5"
        placeholder="请输入解答" />
    </el-form-item>
    <el-form-item
      label="显示排序"
      prop="sort">
      <div>
        <el-input-number
          v-model="formData.sort"
          :min="0"
          :max="1000" />
        <div class="text-[#999] text-[12px]">值越大越靠前</div>
      </div>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>
.active {
  --el-input-border-color: var(--el-color-primary);

  :deep(.el-input-group__prepend) {
    background-color: var(--el-color-primary);
    color: var(--el-color-white);
  }
}
</style>
